package com.situ.gym.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.situ.gym.pojo.Course;
import com.situ.gym.pojo.query.CoachCourseQuery;
import com.situ.gym.pojo.vo.CoachCourseVO;
import com.situ.gym.service.ICoachCourseService;
import com.situ.gym.util.Result;
import com.situ.gym.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 教练课程管理控制器
 * 提供教练管理自己课程的所有接口
 *
 * @author ${author}
 * @since 2025-01-27
 */
@RestController
@RequestMapping("/coach/course")
public class CoachCourseController {
    
    @Autowired
    private ICoachCourseService coachCourseService;

    /**
     * 获取当前教练的课程列表
     * @param coachCourseQuery 查询条件
     * @return 分页课程列表
     */
    @GetMapping("/list")
    public Result<IPage<CoachCourseVO>> list(CoachCourseQuery coachCourseQuery) {
        System.out.println("CoachCourseController.list");
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        // 设置查询条件中的教练ID，确保只能查询自己的课程
        coachCourseQuery.setCoachId(coachId);
        
        IPage<CoachCourseVO> page = coachCourseService.list(coachCourseQuery);
        return Result.ok(page);
    }

    /**
     * 添加课程（自动关联到当前教练）
     * @param course 课程信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public Result add(@RequestBody Course course) {
        System.out.println("CoachCourseController.add: " + course);
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        // 设置课程关联的教练ID
        course.setCoachId(coachId);
        
        coachCourseService.save(course);
        return Result.ok("添加成功");
    }

    /**
     * 更新课程（只能更新自己的课程）
     * @param course 课程信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public Result update(@RequestBody Course course) {
        System.out.println("CoachCourseController.update: " + course);
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        // 验证课程是否属于当前教练
        Course existingCourse = coachCourseService.getById(course.getId());
        if (existingCourse == null) {
            return Result.error("课程不存在");
        }
        if (!existingCourse.getCoachId().equals(coachId)) {
            return Result.error("无权限操作此课程");
        }
        
        // 确保更新时教练ID不变
        course.setCoachId(coachId);
        
        coachCourseService.updateById(course);
        return Result.ok("更新成功");
    }

    /**
     * 删除课程（只能删除自己的课程）
     * @param id 课程ID
     * @return 操作结果
     */
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Long id) {
        System.out.println("CoachCourseController.deleteById: " + id);
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        // 验证课程是否属于当前教练
        Course course = coachCourseService.getById(id);
        if (course == null) {
            return Result.error("课程不存在");
        }
        if (!course.getCoachId().equals(coachId)) {
            return Result.error("无权限删除此课程");
        }
        
        coachCourseService.removeById(id);
        return Result.ok("删除成功");
    }

    /**
     * 批量删除课程（只能删除自己的课程）
     * @param ids 课程ID数组
     * @return 操作结果
     */
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Long[] ids) {
        System.out.println("CoachCourseController.deleteAll: " + java.util.Arrays.toString(ids));
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        // 验证所有课程是否属于当前教练
        for (Long id : ids) {
            Course course = coachCourseService.getById(id);
            if (course == null) {
                return Result.error("课程不存在: " + id);
            }
            if (!course.getCoachId().equals(coachId)) {
                return Result.error("无权限删除课程: " + id);
            }
        }
        
        coachCourseService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    /**
     * 更新课程状态
     * @param id 课程ID
     * @param status 状态值
     * @return 操作结果
     */
    @PutMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        System.out.println("CoachCourseController.updateStatus: id=" + id + ", status=" + status);
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        // 验证课程是否属于当前教练
        Course course = coachCourseService.getById(id);
        if (course == null) {
            return Result.error("课程不存在");
        }
        if (!course.getCoachId().equals(coachId)) {
            return Result.error("无权限操作此课程");
        }
        
        Course updateCourse = new Course();
        updateCourse.setId(id);
        updateCourse.setStatus(status);
        coachCourseService.updateById(updateCourse);
        return Result.ok("修改成功");
    }

    /**
     * 获取课程详情
     * @param id 课程ID
     * @return 课程详情
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Long id) {
        System.out.println("CoachCourseController.selectById: " + id);
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        // 验证课程是否属于当前教练
        Course course = coachCourseService.getById(id);
        if (course == null) {
            return Result.error("课程不存在");
        }
        if (!course.getCoachId().equals(coachId)) {
            return Result.error("无权限查看此课程");
        }
        
        return Result.ok(course);
    }

    /**
     * 导出课程Excel
     * @param response HTTP响应
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) {
        System.out.println("CoachCourseController.exportExcel");
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        coachCourseService.exportExcel(response, coachId);
    }

    /**
     * 导入课程Excel
     * @param file Excel文件
     * @return 操作结果
     */
    @PostMapping("/importExcel")
    public Result importExcel(MultipartFile file) {
        System.out.println("CoachCourseController.importExcel");
        
        // 获取当前登录教练的ID
        Map<String, Object> tokenMap = ThreadLocalUtil.get();
        Long coachId = Long.valueOf(tokenMap.get("id").toString());
        
        coachCourseService.importExcel(file, coachId);
        return Result.ok("导入成功");
    }
}
